package com.zyh.service.impl;



import com.zyh.entity.Profile;
import com.zyh.service.InteractionService;

import com.zyh.service.MessageService;
import com.zyh.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Set;

@Transactional
@Service
public class InteractionServiceImpl implements InteractionService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MessageService messageService;
    @Override
    public int onStart(Integer postId) {
        Integer userId=JWTUtil.getUserId((String) SecurityUtils.getSubject().getPrincipal());
        redisTemplate.opsForSet().add("post:" + postId + ":start",userId);
        //发送点赞消息
        messageService.addStartMessage(userId,postId,4);
        return 1;
    }

    @Override
    public int unStart(Integer postId) {
        Integer userId=JWTUtil.getUserId((String) SecurityUtils.getSubject().getPrincipal());
        redisTemplate.opsForSet().remove("post:" + postId + ":start",userId);
        return 1;
    }

    @Override
    public boolean existsStar(Integer postId) {
        Integer userId=JWTUtil.getUserId((String) SecurityUtils.getSubject().getPrincipal());
        return redisTemplate.opsForSet().isMember("post:" + postId + ":start",userId).booleanValue();
    }

    @Override
    public int onCollect(Integer postId) {
        Integer userId=JWTUtil.getUserId((String) SecurityUtils.getSubject().getPrincipal());
        redisTemplate.opsForZSet().add(userId+":collect",postId,new Date().getTime());
        redisTemplate.opsForSet().add("post:" + postId + ":collect",userId);
        return 1;
    }
    @Override
    public int unCollect(Integer postId) {
        Integer userId=JWTUtil.getUserId((String) SecurityUtils.getSubject().getPrincipal());
        redisTemplate.opsForZSet().remove(userId+":collect",postId);
        redisTemplate.opsForSet().remove("post:" + postId + ":collect",userId);
        return 0;
    }

    @Override
    public Profile findUserProfile(Integer userId) {
        Profile profile=new Profile();

        profile.setCollects(redisTemplate.opsForZSet().size(userId+":collect").intValue());

        profile.setFollowers(redisTemplate.opsForSet().size(userId+":followers").intValue());

        profile.setFollowings(redisTemplate.opsForSet().size(userId+":followings").intValue());
        return profile;
    }




    @Override
    public boolean existsCollect(Integer postId) {
        Integer userId=JWTUtil.getUserId((String) SecurityUtils.getSubject().getPrincipal());
        return redisTemplate.opsForSet().isMember("post:" + postId + ":collect",userId);
    }



}
